<template>
  <div class="box">
    <div class="main" v-loading="loading">
      <h1 class="title">修改博客</h1>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="90px"
        class="demo-ruleForm"
        size="large"
        label-position="left"
        validate-on-rule-change
        style="width: 100%; padding: 20px 20px 0px"
      >
        <el-form-item label="标题" prop="title" style="width: 100%">
          <el-input
            style="width: 100%"
            type="text"
            v-model="ruleForm.title"
            placeholder="输入标题..."
          ></el-input>
        </el-form-item>

        <el-form-item label="摘要" style="width: 100%">
          <el-input type="textarea" v-model="ruleForm.describe"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content" style="width: 100%">
          <v-md-editor
            v-model="ruleForm.content"
            height="480px"
            placeholder="请输入内容"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
          ></v-md-editor>
        </el-form-item>

        <el-form-item label="封面" prop="coverImage">
          <el-upload
            :action="File_API.OTHER_URL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            class="avatar-uploader"
						:headers="{'Authorization': 'Bearer ' + userStore.token}"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <!-- <el-icon v-else name="UploadFilled" class="avatar-uploader-icon"></el-icon> -->
            <el-icon v-else class="avatar-uploader-icon" color="#009be2">
              <UploadFilled />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="文章类型" prop="type">
          <el-cascader
            v-model="selectedOptions"
            :props="prop"
            :show-all-levels="false"
            @change="selectType"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="标签">
          <el-popover placement="top" width="150" trigger="click" v-model="visibleAdd">
            <el-input
              placeholder="请输入标签"
              @blur="handleInput(tags1)"
              v-model="tags1"
              clearable
            ></el-input>
            <template #reference>
              <el-button>添加文章标签</el-button>
            </template>
          </el-popover>

          <el-popover
            v-for="(tag, index) in ruleForm.tags1"
            :key="tag"
            placement="top"
            width="150"
            trigger="click"
            v-model="visibleTag"
          >
            <div style="text-align: center">
              <el-button @click="deleteTag(index)">删除</el-button>
            </div>
            <template #reference>
              <el-button>{{ tag }}</el-button>
            </template>
          </el-popover>
        </el-form-item>

				<!-- <el-form-item label="审核状态" prop="status">
            <el-select
              v-model="ruleForm.status"
              placeholder="审核状态"
              clearable
              style="width: 200px"
            >
              <el-option label="待审核" value="1" />
              <el-option label="审核通过" value="2" />
              <el-option label="内容违规" value="3" />
            </el-select>
          </el-form-item> -->

        <el-form-item label="可见范围">
          <el-radio-group v-model="ruleForm.visible">
            <el-radio
              v-for="option in optionsVisible"
              :key="option.id"
              :label="option.id"
            >
              {{ option.visibleRange }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item style="width: 100%">
          <div style="width: 100%; display: flex; justify-content: center">
            <el-button type="primary" round @click="commit(ruleFormRef)">
              <el-icon>
                <Edit />
              </el-icon>
              修改博客
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { getVisible } from "@/api/blog";
import { getType2 } from "@/api/blog";
import { getType1 } from "@/api/blog";
import { File_API } from "@/api/file";
import { updatainfo } from "@/api/blog";
import { Article } from "@/api/blog/type";
import { getDetail } from "@/api/blog";
import axios from "axios";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {UploadFilled,Promotion,Plus,Edit} from '@element-plus/icons-vue'
// import { useRouter } from "vue-router";
import { useUserStoreHook } from '@/store/modules/user'

const userStore = useUserStoreHook()

let router = useRouter();

defineComponent({
  components: {
		UploadFilled,
		Promotion,
		Plus,
		Edit,
  },
});

//vue3获取ref
const ruleFormRef = ref<FormInstance>();
const md = ref(null);

//表单
const ruleForm = reactive({
  id: 0,
  title: "",
  type: 0,
  tags1: [],
  visible: 4,
  coverImage: "",
  content: "", // 绑定富文本编辑器的内容
  describe: "",
	status: 0,
});

//初始博客实体
const blog = ref<Article>({
  id: 0,
  authorUsername: "",
  title: " ",
  type: 0,
  tag: [],
  browseRecord: 0,
  createTime: "",
  publishTime: "",
  coverImage: "",
  content: "",
  describe: "",
  likeRecord: 0,
  noc: 0,
  liked: false,
  collected: false,
  typeName: "",
  status: 0,
  visible: 0,
});

//封面显示
const imageUrl = ref("");

//类型
const selectedOptions = ref([]);

const prop = reactive({
  lazy: true,
  expandTrigger: "hover",
  // checkStrictly: true,
  lazyLoad(node: any, resolve: any) {
    setTimeout(() => {
      if (node.level == 0) {
        getType1()
          .then((res) => {
            console.log(res);
            const firstLevelOptions = res.data.categories.map((item) => {
              return {
                value: item.id,
                label: item.name,
                leaf: false,
                id: item.id,
              };
            });
            resolve(firstLevelOptions);
          })
          .catch((error) => {});
      } else if (node.level == 1) {
        console.log(node.data.id);

        getType2(node.data.id)
          .then((res) => {
            console.log(res);
            const childOptions = res.data.categories.map((item) => {
              return {
                value: item.id,
                label: item.name,
                leaf: true,
                id: item.id,
              };
            });
            resolve(childOptions);
          })
          .catch((error) => {});
      }
    }, 1000);
  },
});

//可见范围
const optionsVisible = ref([]);

//标签
const visibleAdd = ref(false);
const visibleTag = ref(false);
const tags1 = ref("");

//表单验证
const validateType = (rule: any, value: any, callback: any) => {
  console.log("value", value, ruleForm.type);
  if (value === 0) {
    return callback(new Error("请选择一个类型"));
  } else {
    callback();
  }
};

//表单验证
const validateContent = (rule: any, value: any, callback: any) => {
  if (value === "") {
    return callback(new Error("请输入内容！！"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<typeof ruleForm>>({
  title: [{ required: true, message: "请输入标题！", trigger: "blur" }],
  type: [{ required: true, validator: validateType, trigger: "blur" }],
  content: [{ required: true, validator: validateContent, trigger: "blur" }],
});

const handleInput = (value: any) => {
  console.log("放入标签值", value);
  ruleForm.tags1.push(value);
  // data.visibleAdd = false;
  tags1.value = "";
};

const deleteTag = (index: any) => {
  ruleForm.tags1.splice(index, 1);
};

onMounted(async () => {
  GetVisible();
  getBlog();
});

const getBlog = async () => {
  const route = useRoute();
  console.log(route.params.id);
  try {
    const res = await getDetail(route.params.id);
    console.log(res);
    blog.value = res.data.posting;
    initial();
  } catch (error) {
    Promise.reject(error);
  }
};

const initial = () => {
  ruleForm.id = blog.value.id;
  ruleForm.title = blog.value.title;
  ruleForm.describe = blog.value.describe;
  ruleForm.content = blog.value.content;
  ruleForm.coverImage = blog.value.coverImage;
  imageUrl.value = blog.value.coverImage;
  ruleForm.type = blog.value.type;
  ruleForm.tags1 = blog.value.tag;
  ruleForm.visible = blog.value.visible;
	ruleForm.status = blog.value.status;
};

const GetVisible = async () => {
  try {
    const res = await getVisible();
    console.log(res);
    optionsVisible.value = res.data.visibleTypeList;
  } catch (error) {
    Promise.reject(error);
  }
};

const selectType = (value: any[]) => {
  console.log("hello", selectedOptions.value[1]);
  ruleForm.type = selectedOptions.value[1];
};

const handleAvatarSuccess = (res: any, file: any) => {
  imageUrl.value = URL.createObjectURL(file.raw);
  console.log(res.data.url);
  ruleForm.coverImage = res.data.url;
};

const beforeAvatarUpload = () => {};

// // const $imgAdd
// const imgAdd = (pos: any, file: any) => {
//   console.log('上传图片断点')
//   console.log(`${File_API.OTHER_URL}`)
//   // 第一步.将图片上传到服务器.
//   let formdata = new FormData()
//   formdata.append('file', file)
//   axios({
//     url: `${File_API.OTHER_URL}`,
//     method: 'post',
//     data: formdata,
//     headers: { 'Content-Type': 'multipart/form-data' },
//   }).then((res) => {
//     // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
//     // $vm.$img2Url 详情见本页末尾
//     console.log(res.data.data.url)
//     console.log(md)
//     md.value.$img2Url(pos, res.data.data.url)
//   })
// }

const handleUploadImage = (event: Event, insertImage: any, files: File[]) => {
  for (let i in files) {
    const formData = new FormData();
    formData.append("file", files[i]);
    axios.post(`${File_API.OTHER_URL}`, formData).then(
      (response) => {
        const { data } = response.data;
        insertImage({
          url: data.url,
          desc: "desc",
        });
      },
      (error) => {
        ElMessage.error(error.message);
      }
    );
  }
};

const commit = (formEl: FormInstance | undefined) => {
  // console.log('提交')
  if (!formEl) {
    console.log("表单没找到");
    return;
  }
  formEl.validate(async (valid) => {
    console.log(ruleForm.tags1);
    if (valid) {
      console.log("submit!");
      try {
        console.log(ruleForm);
        const res = await updatainfo(ruleForm);
        console.log(res);
        ElMessageBox.alert(res.message, "温馨提示", {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: "确认",
          callback: (action: Action) => {},
        });
      } catch (error) {
        Promise.reject(error);
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
	router.go(-1);
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped lang="scss">
h1 {
  color: blue;
}

.box {
  display: flex;
  justify-content: center;
  width: 100%;

  .main {
    width: 1180px;
    border-radius: 8px;
    background-color: white;
    padding: 26px 32px;

    .title {
      font-size: 20px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }
}
.tag {
  margin: 10px;
}
</style>

<!-- 饿了么的样式写在这里避免不生效 -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #807d7d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #409eff;
  width: 268px;
  height: 178px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 268px;
  height: 178px;
  display: block;
}

.rounded-button {
  display: inline-block;
  padding: 13px 23px 13px 23px;
  /* 根据需要调整按钮的内边距 */
  border-radius: 17px;
  /* 设置按钮的圆角半径 */
  background-color: #f0f0f0;
  /* 设置按钮的背景色 */
  color: #333;
  /* 设置按钮的文字颜色 */
  font-size: 16px;
  /* 设置按钮的文字大小 */
  text-decoration: none;
  /* 去掉按钮的下划线 */
  cursor: pointer;
  /* 鼠标移上按钮时显示手形光标 */
  padding: 13px 23px 13px 23px;
  /* 根据需要调整按钮的内边距 */
  border-radius: 17px;
  /* 设置按钮的圆角半径 */
  background-color: #f0f0f0;
  /* 设置按钮的背景色 */
  color: #333;
  /* 设置按钮的文字颜色 */
  font-size: 16px;
  /* 设置按钮的文字大小 */
  text-decoration: none;
  /* 去掉按钮的下划线 */
  cursor: pointer;
  /* 鼠标移上按钮时显示手形光标 */
}

/* 鼠标移上按钮时的样式 */
.rounded-button:hover {
  background-color: #c1daf3;
  /* 修改按钮的背景色 */
  color: #fff;
  /* 修改按钮的文字颜色 */
  background-color: #c1daf3;
  /* 修改按钮的背景色 */
  color: #fff;
  /* 修改按钮的文字颜色 */
}
</style>
